package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zzyl.common.thread.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;
    /**
     * 目标方法之前拦截
     * @param request
     * @param response
     * @param handler
     * @return  true放行，false拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是Controller层的请求，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //1.从请求头对象中获取令牌
        String authorization = request.getHeader("authorization");
        if (StringUtils.isEmpty( authorization)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        //2.解析令牌
        Claims claims = tokenService.parseToken(authorization);
        if (ObjectUtil.isEmpty(claims)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        //3.获取用户信息
        Long userId = MapUtil.get(claims, "userId", Long.class);
        //4.存入到ThreadLocal对象中
        UserThreadLocal.set(userId);
        return true;
    }

    /**
     * 所有的目标方法执行之后最后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
